//
//  JYPersonalTaxViewController.swift
//  JYCalculate
//
//  Created by 何治军 on 2018/10/30.
//  Copyright © 2018 何治军. All rights reserved.
//

import UIKit

class JYPersonalTaxViewController: JYBaseViewController ,UITableViewDataSource,UITableViewDelegate {
    
    
    /// 其他数据
    var caculateDataArray:[[JYHouseLoanModel]] = [[],[]]
    
    /// 五险一金的数据
    private var extraArray:[JYHouseLoanModel] = []
    
    /// 是否展示五险一金
    private var showExtraSection:Bool = false

    /// 所在城市
    private var cityArray:[JYHouseLoanModel] {
        var array:[JYHouseLoanModel]=[]
        let model = JYHouseLoanModel()
        model.title = "所在城市"
        model.descri = "北京市"
        array.append(model)
        return array
    }
    
    /// 个税起征点
    private var startTaxArray:[JYHouseLoanModel] {
        var array:[JYHouseLoanModel]=[]
        let titles = ["(本地)","(外籍及港、澳、台)"]
        for index in 0..<titles.count {
            let model = JYHouseLoanModel()
            model.title = "个税起征点"
            model.descri = index == 0 ? "5000" : "4800"
            model.defaultDescri = titles[index]
            array.append(model)
        }
        return array
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = Localized("function-personal-tax")
        NotificationCenter.default.addObserver(self, selector: #selector(changeForKeyBoard(_:)), name: NSNotification.Name(rawValue: "UIKeyboardWillShowNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector:  #selector(changeForKeyBoard(_:)), name: NSNotification.Name(rawValue: "UIKeyboardWillHideNotification"), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    override func setUpUI() {
        tableView.tableHeaderView = topView
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(JYHouseLoanCell.self, forCellReuseIdentifier: "JYHouseLoanCell")
        self.view.addSubview(tableView)
        self.view.addSubview(caculateView)
    }
    
    override func setDefaultInfo() {
        
        let model00 = JYHouseLoanModel()
        model00.title = "收入金额"
        model00.defaultDescri = "请输入金额"
        self.caculateDataArray[0].append(model00)
        self.caculateDataArray[0].append(self.cityArray[0])
        self.caculateDataArray[0].append(self.startTaxArray[0])
        let model03 = JYHouseLoanModel()
        model03.title = "五险一金"
        self.caculateDataArray[0].append(model03)
        
        let extraTitleArray:[String] = ["公积金","医疗","养老","失业","工伤","生育"]
        let extraTitleDes:[String] = ["12.00","2.00","8.00","0.20","0.00","0.00"]
        for index in 0 ..< extraTitleArray.count {
            let model = JYHouseLoanModel()
            model.identification = "\(index)"
            model.title = extraTitleArray[index]
            model.defaultDescri = extraTitleDes[index]
            model.descri = extraTitleDes[index]
            self.extraArray.append(model)
        }
        
        let model10 = JYHouseLoanModel()
        model10.title = "奖金金额"
        model10.defaultDescri = "请输入金额"
        self.caculateDataArray[1].append(model10)
        let model11 = JYHouseLoanModel()
        model11.title = "工资收入"
        model11.defaultDescri = "请输入金额"
        self.caculateDataArray[1].append(model11)
        
        self.tableView.reloadData()
    }
    
    override func setTheLayout() {
        tableView.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.top.mas_equalTo()(self.view)
            make?.bottom.mas_equalTo()(self.caculateView.mas_top)
        }
        caculateView.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.bottom.mas_equalTo()(self.view)
            make?.height.mas_equalTo()(88)
            
        }
    }
    
    //MARK: - UITableViewDataSource,UITableViewDelegate
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.topView.segment.selectedSegmentIndex == 0 && self.showExtraSection ? 2 : 1;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.topView.segment.selectedSegmentIndex == 0 && self.showExtraSection && section == 1  {
            return self.extraArray.count;
        }else{
            return self.caculateDataArray[self.topView.segment.selectedSegmentIndex].count;
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.topView.segment.selectedSegmentIndex == 0 {
            let cell = JYHouseLoanCell.init(style: .default, reuseIdentifier: "JYHouseLoanCell")
            if indexPath.section == 0 {
                cell.model = self.caculateDataArray[0][indexPath.row]
                if indexPath.row == 0 {
                    cell.accessoryType = .none
                    cell.cellMode = .one
                }else{
                    if indexPath.row == 3 {
                        cell.accessoryType = .detailButton
                        cell.tintColor = JYNavigationBarColor
                    }else{
                        cell.accessoryType = .disclosureIndicator
                    }
                    cell.cellMode = .normal
                }
            }else{
                cell.model = self.extraArray[indexPath.row]
                cell.accessoryType = .none
                cell.cellMode = .two
            }
            return cell
        }else{
            let cell = JYHouseLoanCell.init(style: .default, reuseIdentifier: "JYHouseLoanCell")
            cell.model = self.caculateDataArray[1][indexPath.row]
            cell.accessoryType = .none
            cell.cellMode = .one
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        hiddenKeyBoard()
        if self.topView.segment.selectedSegmentIndex == 0 {
            if indexPath.row == 1 {
                let vc = JYCityListViewController()
                vc.currentSelectedModel = JYCityModel.modelWithModel(self.caculateDataArray[0][1])
                vc.selectedModelBlock = { [weak self] model in
                    let strongSelf = self
                    strongSelf?.caculateDataArray[0][1] = model.changeToJYInfoModel()
                    strongSelf?.changeTheLoanType()
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }else if indexPath.row == 2 {
                let vc = JYHouseLoanListViewController()
                vc.dataArray = self.startTaxArray
                vc.currentSelectedModel = self.caculateDataArray[0][2]
                vc.selectedModelBlock = { [weak self] model in
                    let strongSelf = self
                    strongSelf?.caculateDataArray[0][2] = model
                    strongSelf?.changeTheLoanType()
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }else if indexPath.row == 3 {
                self.showExtraSection = !self.showExtraSection
                self.tableView.reloadData()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        hiddenKeyBoard()
    }

    //键盘改变事接收的通知事件
    @objc func changeForKeyBoard(_ noti:NSNotification){
        let duration = noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        if noti.name.rawValue == "UIKeyboardWillShowNotification" {
            let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as! CGRect
            UIView.animate(withDuration: duration) {
                self.view.transform = CGAffineTransform(translationX: 0, y: -rect.height)
                self.tableView.contentInset = UIEdgeInsets(top: rect.height, left: 0, bottom: 0, right: 0)
                self.tableView.bounces = true
            }
        }else{
            UIView.animate(withDuration: duration) {
                self.view.transform = CGAffineTransform(translationX: 0, y: 0)
                self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
                self.tableView.bounces = false
            }
        }
    }
    //MARK: - 修改贷款方式
    @objc func changeTheLoanType(){
        hiddenKeyBoard()
        self.tableView.reloadData()
    }
    
    //MARK: - 开始计算结果
    @objc func caculate() {
        hiddenKeyBoard()
        
        let vc = JYPersonalTaxResultViewController()

        if self.topView.segment.selectedSegmentIndex == 0 {
            if self.caculateDataArray[0][0].descri == "" {
                let vc = UIAlertController(title: "请输入贷款额度", message: nil, preferredStyle: .alert)
                let cancel = UIAlertAction(title: "确定", style: .cancel, handler: nil)
                vc.addAction(cancel)
                self.present(vc, animated: true, completion: nil)
                return
            }
            vc.caculateDic = ["caculateType":"0","money":self.caculateDataArray[0][0].descri,"startLine":self.caculateDataArray[0][2].descri,"accumulation":self.extraArray[0].descri,"first":self.extraArray[1].descri,"second":self.extraArray[2].descri,"third":self.extraArray[3].descri,"fourth":self.extraArray[4].descri,"fifth":self.extraArray[5].descri]

        }else{
            if self.caculateDataArray[1][0].descri == "" || self.caculateDataArray[1][1].descri == "" {
                let vc = UIAlertController(title: "请输入贷款额度", message: nil, preferredStyle: .alert)
                let cancel = UIAlertAction(title: "确定", style: .cancel, handler: nil)
                vc.addAction(cancel)
                self.present(vc, animated: true, completion: nil)
                return
            }
            vc.caculateDic = ["caculateType":"1","money1":self.caculateDataArray[1][0].descri,"money2":self.caculateDataArray[1][1].descri,"startLine":self.caculateDataArray[0][2].descri,"accumulation":self.extraArray[0].descri,"first":self.extraArray[1].descri,"second":self.extraArray[2].descri,"third":self.extraArray[3].descri,"fourth":self.extraArray[4].descri,"fifth":self.extraArray[5].descri]
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK: -隐藏键盘
    @objc private func hiddenKeyBoard() {
        UIApplication.shared.keyWindow?.endEditing(true)
    }
    
    //MARK: - 组件
    private lazy var topView:JYHouseLoanTopView = {
        let v = JYHouseLoanTopView.init(frame: CGRect(x: 0, y: 0, width: 10, height: 60))
        v.titleArray = ["个人所得税","年终奖"]
        v.segment.selectedSegmentIndex = 0
        v.topLine.isHidden = false
        v.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hiddenKeyBoard)))
        v.segment.addTarget(self, action: #selector(changeTheLoanType), for: .valueChanged)
        return v
    }()
    
    private lazy var tableView:UITableView = {
        let tab = UITableView()
        tab.separatorStyle = .none
        tab.backgroundColor = JYVCBackGroundColor
        return tab
    }()

    private lazy var caculateView:JYHouseLoanCaculateBtnView = {
        let v = JYHouseLoanCaculateBtnView()
        v.caculateBtn.addTarget(self, action: #selector(caculate), for: .touchUpInside)
        return v
    }()
    
}
